package com.pocketsweet.ui.uilib.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.SaveCallback;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Profile;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.MyRatingBar;
import com.pocketsweet.utils.ToolKits;

/**
 * 
 * @author Kam
 * 
 */
public class MyEvaluationAdapter extends BaseListAdapter<MLOrder> {
	public MyEvaluationAdapter(Context ctx) {
		super(ctx);
	}

	public MyEvaluationAdapter(Context ctx, List<MLOrder> datas) {
		super(ctx, datas);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_appraise, parent,
					false);
			viewHolder = new ViewHolder(convertView);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.refreshView(datas.get(position), position);
		return convertView;
	}

	public class ViewHolder implements View.OnClickListener {
		ImageView imgAvatar;
		TextView tvuserName;
		TextView tvOrderTime;
		TextView tvOrderFinishTime;
		TextView tvGoToComment;
		TextView tvAppraise;
		TextView tvDefault;
		LinearLayout grade;
		RatingBar rating_bar;
		int score = 0;
		MLUser mlUser;
		MLOrder mlOrder;
		private View parent;

		Handler myHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					rating_bar.setRating(score);
					// rating_bar.setNumStars(score);
					tvGoToComment.setVisibility(View.GONE);
					rating_bar.setVisibility(View.VISIBLE);
					tvDefault.setVisibility(View.GONE);
					break;
				}
				super.handleMessage(msg);
			}
		};

		private ViewHolder(View parent) {
			this.parent = parent;
			initView(parent);
		}

		public void initView(View parent) {
			imgAvatar = (ImageView) parent.findViewById(R.id.imgAvatar);
			tvuserName = (TextView) parent.findViewById(R.id.tvuserName);
			tvOrderTime = (TextView) parent.findViewById(R.id.tvOrderTime);
			tvDefault = (TextView) parent.findViewById(R.id.tvDefault);
			tvGoToComment = (TextView) parent.findViewById(R.id.tvGoToComment);
			tvOrderFinishTime = (TextView) parent
					.findViewById(R.id.tvOrderFinishTime);
			tvAppraise = (TextView) parent.findViewById(R.id.tvAppraise);
			grade = (LinearLayout) parent.findViewById(R.id.grade);
			rating_bar = (RatingBar) parent.findViewById(R.id.rating_appraise);
		}

		public void refreshView(MLOrder mlOrder, int i) {
			this.mlOrder = mlOrder;
			mlUser = mlOrder.getSponsor();
			String avatar = mlUser.getAvatarUrl();
			if (avatar != null && !avatar.equals("")) {
				UserService.displaySquare(avatar, imgAvatar);
			} else {
				imgAvatar.setImageResource(R.drawable.default_user_avatar);
			}
			if (mlOrder.getCommentStatus() != 0) {
				if (mlOrder.getCommentStatus() < 6) {
					rating_bar.setRating(mlOrder.getCommentStatus());
					// rating_bar.setMax(mlOrder.getCommentStatus());
					// rating_bar.setNumStars(mlOrder.getCommentStatus());
					tvGoToComment.setVisibility(View.GONE);
					rating_bar.setVisibility(View.VISIBLE);
					tvDefault.setVisibility(View.GONE);
				} else if (mlOrder.getCommentStatus() == 6) {// 默认好评
					rating_bar.setRating(5);
					// rating_bar.setMax(mlOrder.getCommentStatus());
					// rating_bar.setNumStars(5);
					tvGoToComment.setVisibility(View.GONE);
					rating_bar.setVisibility(View.VISIBLE);
					tvDefault.setVisibility(View.VISIBLE);
					tvDefault.setText("系统默认好评");
				}
			} else {
				rating_bar.setVisibility(View.GONE);
				tvDefault.setText("对方未评价");
				tvDefault.setVisibility(View.VISIBLE);
				tvGoToComment.setVisibility(View.GONE);
				tvDefault.setVisibility(View.VISIBLE);
			}
			// 设置姓名
			tvOrderTime.setText(ToolKits.translateMinToStandard((long) mlOrder
					.getPeriod()) + "订单");// 几分钟订单
			tvOrderFinishTime.setText(ToolKits.getTimeDiff(mlOrder
					.getUpdatedAt()));// 几分钟之前
			tvuserName.setText(mlUser.getNickname());
			parent.setOnClickListener(this);
			tvGoToComment.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			if (v.equals(tvGoToComment)) {
				final MyRatingBar ratingBar = new MyRatingBar(ctx);
				MyAlertDialog dialog = new MyAlertDialog(ctx).builder()
						.setTitle("给Ta评个分").setView(ratingBar)
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {
							}
						});
				dialog.setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(View v) {
						score = ratingBar.getScore();
						mlOrder.setCommentStatus(score);
						mlOrder.setStatus(C.ORDER_STATUS_FINISH);
						mlOrder.saveInBackground(new SaveCallback() {

							@Override
							public void done(AVException arg0) {
								// TODO Auto-generated method stub
								if (arg0 == null) {
									double price = 0;
									if (score <= 3) {
										price = 0;
									} else if (score == 4) {
										price = mlOrder.getCost() * 0.8;
									} else if (score == 5) {
										price = mlOrder.getCost();
									}
									// 调用云代码给恋爱体验师钱
									Map<String, Object> params = new HashMap<String, Object>();
									params.put("price", price);
									params.put("userId", mlOrder.getWinner()
											.getObjectId());
									AVCloud.callFunctionInBackground(
											"BalanceAccount", params,
											new FunctionCallback<Object>() {

												@Override
												public void done(Object arg0,
														AVException e) {
													// TODO Auto-generated
													// method stub
													if (e == null) {
														Message message = new Message();
														message.what = 0;
														myHandler
																.sendMessage(message);
													}

												}
											});

								}
							}
						});

					}
				});
				dialog.show();
			}else if(v.equals(parent)){
				String selectedUserId = mlOrder.getSponsor().getObjectId();
				Intent intent = new Intent(ctx, Profile.class);
				intent.putExtra("userId", selectedUserId);
				intent.putExtra("nickname", mlOrder.getWinner().getNickname());
				ctx.startActivity(intent);
			}
		}
	}
}
